package api

import (
	"exam12_23/internal/api/request"
	"exam12_23/internal/models/service"
	"exam12_23/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func UserRegister(c *gin.Context) {
	var json *request.User
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	register, s := service.UserRegister(json)
	if s != "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": s,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "注册成功",
		"data":    register,
	})

}

func UserLogin(c *gin.Context) {
	var json *request.User
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	register, s := service.UserLogin(json)
	if s != "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": s,
		})
		return
	}

	handler, _ := pkg.TokenHandler(strconv.Itoa(int(register)))

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "登录成功",
		"data":    handler,
	})
}

func UserList(c *gin.Context) {
	var json *request.UserList
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	list := service.UserList(json)

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "用户展示成功",
		"data":    list,
	})

}
